package com.lehecai.core.search.api.impl;

import com.lehecai.core.search.api.SearchApiConstant;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Insert操作时的Body封装
 * User: sunshow
 * Date: 13-4-1
 * Time: 上午8:53
 */
public class InsertSearchApiRequestBody extends AbstractSearchApiRequestBody {

    /**
     * 要插入的字段名
     */
    private String[] field;

    private List<Object[]> valueList = new ArrayList<Object[]>();

    /**
     * 数据已存在时是否强制覆盖
     */
    private boolean force;

    @Override
    public JSON toJSON() {
        JSONObject jsonObject = new JSONObject();

        JSONArray fieldArray = new JSONArray();
        for (String f : field) {
            fieldArray.add(f);
        }
        jsonObject.put(SearchApiConstant.API_PARAMETER_INSERT_FIELD, fieldArray);
        
        JSONArray valueArray = new JSONArray();
        for (Object[] value : valueList) {
            JSONArray valueItem = new JSONArray();
            for (Object o : value) {
                valueItem.add(o);
            }
            valueArray.add(valueItem);
        }
        jsonObject.put(SearchApiConstant.API_PARAMETER_INSERT_VALUE, valueArray);

        if (this.isForce()) {
            jsonObject.put(SearchApiConstant.API_PARAMETER_INSERT_FORCE, this.isForce());
        }

        return jsonObject;
    }

    public void insertValue(Object[] value) {
        this.valueList.add(value);
    }


    public void insertValue(Object[][] values) {
        for (Object[] value : values) {
            this.insertValue(value);
        }
    }

    public void insertValue(List<Object[]> valueList) {
        this.valueList.addAll(valueList);
    }

    public void setField(String[] field) {
        this.field = field;
    }

    public boolean isForce() {
        return force;
    }

    public void setForce(boolean force) {
        this.force = force;
    }
}
